<template>
  <div class="stock-out-form">
    <el-page-header @back="goBack" :title="isEdit ? '编辑出库单' : '新建出库单'">
      <template #content>
        <span class="page-header-title">{{ isEdit ? '编辑出库单' : '新建出库单' }}</span>
      </template>
    </el-page-header>
    
    <div class="page-content" v-loading="loading">
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px" 
        class="stock-out-form"
        v-if="!loading"
      >
        <!-- 基本信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <h3>基本信息</h3>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="出库单号" prop="orderNumber">
                <el-input 
                  v-model="form.orderNumber" 
                  placeholder="系统自动生成" 
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="出库类型" prop="orderType">
                <el-select 
                  v-model="form.orderType" 
                  placeholder="请选择出库类型" 
                  style="width: 100%"
                >
                  <el-option 
                    v-for="(name, value) in orderTypes" 
                    :key="value" 
                    :label="name" 
                    :value="Number(value)" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="出库日期" prop="orderDate">
                <el-date-picker
                  v-model="form.orderDate"
                  type="datetime"
                  placeholder="选择出库日期"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="仓库" prop="warehouseId">
                <el-select 
                  v-model="form.warehouseId" 
                  placeholder="请选择仓库" 
                  style="width: 100%"
                  filterable
                >
                  <el-option 
                    v-for="warehouse in warehouses" 
                    :key="warehouse.id" 
                    :label="warehouse.name" 
                    :value="warehouse.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总金额" prop="totalAmount">
                <el-input 
                  v-model="form.totalAmount" 
                  placeholder="根据商品明细自动计算" 
                  disabled
                >
                  <template #prefix>¥</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用途" prop="purpose" v-if="form.orderType === 2 || form.orderType === 4">
                <el-input 
                  v-model="form.purpose" 
                  placeholder="请输入出库用途"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="备注" prop="remarks">
            <el-input 
              v-model="form.remarks" 
              type="textarea" 
              :rows="2" 
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-card>
        
        <!-- 商品明细 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <h3>商品明细</h3>
              <div class="header-actions">
                <el-button type="primary" @click="handleAddItem">
                  <el-icon><Plus /></el-icon>
                  添加商品
                </el-button>
              </div>
            </div>
          </template>
          
          <el-table
            :data="form.items"
            border
            style="width: 100%"
          >
            <el-table-column label="序号" type="index" width="50" />
            <el-table-column label="商品" min-width="200">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.productId" 
                  placeholder="请选择商品" 
                  style="width: 100%"
                  filterable
                  @change="handleProductChange(scope.row)"
                >
                  <el-option 
                    v-for="product in products" 
                    :key="product.id" 
                    :label="product.name" 
                    :value="product.id" 
                  >
                    <div class="product-option">
                      <span>{{ product.name }}</span>
                      <span class="product-option-desc">{{ product.sku }} | {{ product.category?.name }}</span>
                    </div>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="当前库存" width="100">
              <template #default="scope">
                {{ getProductStock(scope.row.productId) }}
              </template>
            </el-table-column>
            <el-table-column label="数量" width="150">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.quantity" 
                  :min="0.01" 
                  :precision="2"
                  @change="calculateItemTotal(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="单位" width="100">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.unit" 
                  placeholder="单位"
                />
              </template>
            </el-table-column>
            <el-table-column label="成本价" width="150">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.costPrice" 
                  placeholder="成本价"
                  @input="calculateItemTotal(scope.row)"
                >
                  <template #prefix>¥</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="小计" width="150">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.totalPrice" 
                  placeholder="小计"
                  disabled
                >
                  <template #prefix>¥</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="批次号" width="150">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.batchNumber" 
                  placeholder="批次号"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="150">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.remarks" 
                  placeholder="备注"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  icon="Delete"
                  circle
                  @click="handleRemoveItem(scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
          
          <div class="table-footer">
            <div class="table-summary">
              <span>合计: {{ form.items.length }} 种商品, 总金额: ¥{{ form.totalAmount || '0.00' }}</span>
            </div>
          </div>
        </el-card>
        
        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="saveAsDraft">保存为草稿</el-button>
          <el-button type="success" @click="saveAndConfirm">保存并确认</el-button>
        </div>
      </el-form>
    </div>
    
    <!-- 选择商品对话框 -->
    <el-dialog
      v-model="productDialogVisible"
      title="添加商品"
      width="70%"
    >
      <div class="product-search">
        <el-input
          v-model="productSearchKeyword"
          placeholder="搜索商品名称、条码或SKU"
          prefix-icon="Search"
          clearable
          @keyup.enter="searchProducts"
        />
      </div>
      
      <el-table
        :data="productSearchResults"
        border
        style="width: 100%"
        height="400px"
        @row-click="handleSelectProduct"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="商品名称" min-width="200" />
        <el-table-column prop="sku" label="SKU" width="120" />
        <el-table-column prop="category.name" label="分类" width="120" />
        <el-table-column prop="stockUnit" label="单位" width="80" />
        <el-table-column prop="costPrice" label="成本价" width="120">
          <template #default="scope">
            <span>{{ formatPrice(scope.row.costPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stockQuantity" label="当前库存" width="120" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click.stop="handleSelectProduct(scope.row)"
              :disabled="scope.row.stockQuantity <= 0"
            >
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getStockOutOrderById, 
  createStockOutOrder, 
  updateStockOutOrder, 
  confirmStockOutOrder,
  getAllWarehouses
} from '@/api/inventory';
import { getAllProducts } from '@/api/product';
import { formatPrice } from '@/utils/format';

export default {
  name: 'StockOutForm',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const formRef = ref(null);
    
    // 状态
    const loading = ref(false);
    const isEdit = computed(() => !!route.params.id);
    const warehouses = ref([]);
    const products = ref([]);
    
    // 商品选择对话框
    const productDialogVisible = ref(false);
    const productSearchKeyword = ref('');
    const productSearchResults = ref([]);
    
    // 出库单类型映射
    const orderTypes = {
      1: '销售出库',
      2: '报损出库',
      3: '调拨出库',
      4: '其他出库'
    };
    
    // 表单数据
    const form = reactive({
      id: null,
      orderNumber: '系统自动生成',
      orderType: 1,
      warehouseId: null,
      totalAmount: '0.00',
      purpose: '',
      orderDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
      remarks: '',
      items: []
    });
    
    // 表单验证规则
    const rules = {
      orderType: [
        { required: true, message: '请选择出库类型', trigger: 'change' }
      ],
      warehouseId: [
        { required: true, message: '请选择仓库', trigger: 'change' }
      ],
      orderDate: [
        { required: true, message: '请选择出库日期', trigger: 'blur' }
      ],
      purpose: [
        { required: (form) => form.orderType === 2 || form.orderType === 4, message: '请输入出库用途', trigger: 'blur' }
      ]
    };
    
    // 初始化数据
    const initialize = async () => {
      loading.value = true;
      try {
        // 加载基础数据
        const [warehouseRes, productRes] = await Promise.all([
          getAllWarehouses(),
          getAllProducts({ pageSize: 1000 })
        ]);
        
        warehouses.value = warehouseRes.data;
        products.value = productRes.data.items;
        
        // 如果是编辑模式，加载出库单数据
        if (isEdit.value) {
          const stockOutRes = await getStockOutOrderById(route.params.id);
          Object.assign(form, stockOutRes.data);
          // 确保items是一个数组
          if (!form.items || !Array.isArray(form.items)) {
            form.items = [];
          }
        }
      } catch (error) {
        console.error('Failed to initialize form:', error);
        ElMessage.error('加载数据失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 获取商品当前库存
    const getProductStock = (productId) => {
      if (!productId) return '0';
      const product = products.value.find(p => p.id === productId);
      return product ? `${product.stockQuantity || 0} ${product.stockUnit || ''}` : '0';
    };
    
    // 计算商品明细小计
    const calculateItemTotal = (item) => {
      if (item.quantity && item.costPrice) {
        item.totalPrice = (parseFloat(item.quantity) * parseFloat(item.costPrice)).toFixed(2);
      } else {
        item.totalPrice = '0.00';
      }
      calculateTotal();
    };
    
    // 计算总金额
    const calculateTotal = () => {
      if (form.items && form.items.length > 0) {
        form.totalAmount = form.items.reduce((total, item) => {
          return total + (parseFloat(item.totalPrice) || 0);
        }, 0).toFixed(2);
      } else {
        form.totalAmount = '0.00';
      }
    };
    
    // 添加商品项
    const handleAddItem = () => {
      productDialogVisible.value = true;
      // 过滤出有库存的商品
      productSearchResults.value = products.value.filter(p => parseFloat(p.stockQuantity || 0) > 0);
    };
    
    // 移除商品项
    const handleRemoveItem = (index) => {
      form.items.splice(index, 1);
      calculateTotal();
    };
    
    // 商品变更时触发
    const handleProductChange = (item) => {
      if (item.productId) {
        const product = products.value.find(p => p.id === item.productId);
        if (product) {
          item.unit = product.stockUnit || '';
          item.costPrice = product.costPrice || '0.00';
          calculateItemTotal(item);
        }
      }
    };
    
    // 搜索商品
    const searchProducts = () => {
      if (!productSearchKeyword.value) {
        // 过滤出有库存的商品
        productSearchResults.value = products.value.filter(p => parseFloat(p.stockQuantity || 0) > 0);
        return;
      }
      
      const keyword = productSearchKeyword.value.toLowerCase();
      productSearchResults.value = products.value.filter(product => {
        return (
          (parseFloat(product.stockQuantity || 0) > 0) && 
          (
            product.name.toLowerCase().includes(keyword) ||
            (product.sku && product.sku.toLowerCase().includes(keyword)) ||
            (product.barcode && product.barcode.toLowerCase().includes(keyword))
          )
        );
      });
    };
    
    // 选择商品
    const handleSelectProduct = (product) => {
      // 检查商品是否已经添加
      const existingItem = form.items.find(item => item.productId === product.id);
      if (existingItem) {
        ElMessage.warning('该商品已经添加');
        return;
      }
      
      // 检查库存
      if (parseFloat(product.stockQuantity || 0) <= 0) {
        ElMessage.warning(`商品"${product.name}"库存不足，无法添加`);
        return;
      }
      
      const newItem = {
        productId: product.id,
        quantity: 1,
        unit: product.stockUnit || '',
        costPrice: product.costPrice || '0.00',
        totalPrice: product.costPrice || '0.00',
        batchNumber: '',
        remarks: ''
      };
      
      form.items.push(newItem);
      calculateTotal();
      productDialogVisible.value = false;
    };
    
    // 保存为草稿
    const saveAsDraft = async () => {
      await saveForm(false);
    };
    
    // 保存并确认
    const saveAndConfirm = async () => {
      await saveForm(true);
    };
    
    // 保存表单
    const saveForm = async (confirm = false) => {
      if (!formRef.value) return;
      
      await formRef.value.validate(async (valid) => {
        if (!valid) {
          ElMessage.error('请检查表单填写是否正确');
          return;
        }
        
        if (form.items.length === 0) {
          ElMessage.error('请至少添加一个商品');
          return;
        }
        
        // 验证商品明细
        for (const item of form.items) {
          if (!item.productId) {
            ElMessage.error('请选择商品');
            return;
          }
          
          if (!item.quantity || parseFloat(item.quantity) <= 0) {
            ElMessage.error('商品数量必须大于0');
            return;
          }
          
          // 验证库存是否足够
          const product = products.value.find(p => p.id === item.productId);
          if (product && parseFloat(product.stockQuantity || 0) < parseFloat(item.quantity)) {
            ElMessage.error(`商品"${product.name}"库存不足，当前库存:${product.stockQuantity}，需要出库:${item.quantity}`);
            return;
          }
          
          if (!item.unit) {
            ElMessage.error('请输入商品单位');
            return;
          }
          
          if (!item.costPrice || parseFloat(item.costPrice) < 0) {
            ElMessage.error('商品成本价不能为负');
            return;
          }
        }
        
        loading.value = true;
        try {
          let response;
          const data = { ...form };
          
          if (isEdit.value) {
            response = await updateStockOutOrder(form.id, data);
            ElMessage.success('出库单更新成功');
          } else {
            response = await createStockOutOrder(data);
            ElMessage.success('出库单创建成功');
          }
          
          // 如果需要确认出库单
          if (confirm && response.data && response.data.id) {
            try {
              await confirmStockOutOrder(response.data.id);
              ElMessage.success('出库单已确认，商品库存已更新');
            } catch (error) {
              console.error('Failed to confirm stock-out order:', error);
              ElMessage.error('确认出库单失败: ' + (error.response?.data?.message || '未知错误'));
            }
          }
          
          goBack();
        } catch (error) {
          console.error('Failed to save stock-out order:', error);
          ElMessage.error('保存出库单失败');
        } finally {
          loading.value = false;
        }
      });
    };
    
    // 返回上一页
    const goBack = () => {
      router.push('/admin/inventory/stock-out');
    };
    
    onMounted(() => {
      initialize();
    });
    
    return {
      formRef,
      loading,
      isEdit,
      form,
      rules,
      warehouses,
      products,
      orderTypes,
      productDialogVisible,
      productSearchKeyword,
      productSearchResults,
      getProductStock,
      calculateItemTotal,
      calculateTotal,
      handleAddItem,
      handleRemoveItem,
      handleProductChange,
      searchProducts,
      handleSelectProduct,
      saveAsDraft,
      saveAndConfirm,
      goBack,
      formatPrice
    };
  }
};
</script>

<style scoped>
.stock-out-form {
  padding: 20px;
}

.page-header-title {
  font-size: 18px;
  font-weight: bold;
}

.page-content {
  margin-top: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.table-footer {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.table-summary {
  font-size: 16px;
  font-weight: bold;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.product-search {
  margin-bottom: 15px;
}

.product-option {
  display: flex;
  flex-direction: column;
}

.product-option-desc {
  font-size: 12px;
  color: #999;
}
</style> 